package com.thinkersre.controller;

import com.thinkersre.entity.DiscussPost;
import com.thinkersre.entity.Page;
import com.thinkersre.service.ElasticsearchService;
import com.thinkersre.service.LikeService;
import com.thinkersre.service.UserService;
import com.thinkersre.util.ThinkersReConstant;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController implements ThinkersReConstant {
    @Resource
    private ElasticsearchService elasticsearchService;
    //查询点赞数量和作者
    @Resource
    private UserService userService;
    @Resource
    private LikeService likeService;

    //search?keyword=xx
    @GetMapping("/search")
    public String search(String keyword, Page page, Model model){
        //搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResult =
        elasticsearchService.searchDiscussPost(keyword,page.getPageNo()-1, page.getPageSize());
        //聚合数据
        List<Map<String,Object>> discussPostMapList = new ArrayList<>();
        if (searchResult!=null){
            for (DiscussPost discussPost:searchResult){
                Map<String,Object> map = new HashMap<>();
                //帖子
                map.put("post",discussPost);
                //作者
                map.put("user",userService.findUserById(discussPost.getUserId()));
                //点赞数量
                map.put("likeCount",likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId()));

                discussPostMapList.add(map);
            }
        }

        model.addAttribute("discussPosts",discussPostMapList);
        model.addAttribute("keyword",keyword);
        //分页信息
        page.setPath("/search?keyword="+keyword);
        page.setRowsTotal(searchResult==null?0: (int) searchResult.getTotalElements());
        return "/site/search";
    }

}
